<template>
    <div class="visual-container" @mousedown.right.prevent="onRightMouseDown" @contextmenu.prevent>
        <block v-if="modelData" :data="modelData" :position="{ x: 50, y: 50 }" :layer="1" :index="0" />
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import Block from './Block.vue';

const modelData = ref(null);
defineExpose({ setData });
function setData(data) {
    modelData.value = data;
}

// 鼠标拖动页面有关的属性和方法
let isDragging = ref(false);
let startX = ref(0);
let startY = ref(0);
const visualContainer = ref(null);

const onRightMouseDown = (event) => {
    if (event.button === 2) {
        isDragging.value = true;
        startX.value = event.clientX;
        startY.value = event.clientY;
        document.body.style.cursor = 'move';

        document.addEventListener('mousemove', onMouseMove);
        document.addEventListener('mouseup', onMouseUp);
    }
};

const onMouseMove = (event) => {
    if (!isDragging.value) return;

    const dx = event.clientX - startX.value;
    const dy = event.clientY - startY.value;

    visualContainer.value.scrollLeft -= dx;
    visualContainer.value.scrollTop -= dy;

    startX.value = event.clientX;
    startY.value = event.clientY;
};

const onMouseUp = () => {
    isDragging.value = false;
    document.body.style.cursor = ''; // 恢复鼠标样式

    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
};

onMounted(() => {
    visualContainer.value = document.querySelector('.visual-container');
});

onUnmounted(() => {
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
});
</script>

<style scoped>
.visual-container {
    position: relative;
    overflow: auto;
    width: 100%;
    height: 100%;
    border: 1px solid #ddd;
    padding: 20px;
    box-sizing: border-box;
}
</style>
